package cn.tang.tframe.sdm.enums;

/**
 * Created by tanghc on 17/1/24.
 */

import cn.tang.tframe.common.enums.BaseNumEnum;
import cn.tang.tframe.common.utils.lang.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据权限
 */
public enum AuthorityTypeEnum implements BaseNumEnum {
	read(1<<0, "读权限")

	, write(1<<1, "写权限")

	;

	private int num;
	private String key;

	private AuthorityTypeEnum(int num, String key){
		this.num = num;
		this.key = key;
	}

	@Override
	public int getNum() {
		return num;
	}

	@Override
	public String getKey() {
		return key;
	}
	public static Integer fromEnumsToNum(List<AuthorityTypeEnum> tags){
		if(CollectionUtils.isEmpty(tags)){
			return null;
		}
		int i = 0;
		for(AuthorityTypeEnum tag: tags){
			i |= tag.getNum();
		}
		return i;
	}
	public static List<AuthorityTypeEnum> fromNumToEnums(Integer i){
		if(null == i || i == 0){
			return null;
		}
		List<AuthorityTypeEnum> enums = new ArrayList<>();
		AuthorityTypeEnum[] values = AuthorityTypeEnum.values();
		for(AuthorityTypeEnum authorityTypeEnum: values){
			if(hasAuthority(i, authorityTypeEnum)){
				enums.add(authorityTypeEnum);
			}
		}
		return enums;
	}
	public static boolean hasAuthority(Integer i, AuthorityTypeEnum tag){
		if(null == i){
			return false;
		}
		return (i & tag.getNum()) > 0;
	}
}
